<?php
namespace CechargeChannel;

class Aliba extends ChannelAbstract
{
    protected $username = '';
    protected $key      = '';
    protected $secret   = '';
    protected $data     = [];
    public function commit($data)
    {
        $config         = json_decode($data['configjson'], true);
        $this->username = $config['username'];
        $this->key      = $config['key'];
        $this->secret   = $config['secret'];
        $this->data     = $data;
        return $this->phoneBill();

    }

    // 话费充值
    protected function phoneBill()
    {
        $data = [
            'username' => $this->username,
            'key'      => $this->key,
            'orderid'  => $this->data['order_number'],
            'face'     => $this->data['recharge_amount'],
            'account'  => $this->data['mobile'],
            'amount'   => 1,
        ];
        $userkey         = str_replace('=', '', http_build_query($data));
        $data['userkey'] = strtoupper(md5(str_replace('&', '', $userkey) . $this->secret));
        $data['returl']  = urlencode($this->data['callback_url']);
        file_put_contents('Aliba_pay_log.txt', var_export($data, true));
        $res    = $this->http_request($this->data['domain_name'] . '/api/bills', $data);
        $result = json_decode($res, true);
     //   echo '11';
    	// var_dump($result);
        if ($result['code'] == 0 || $result['code'] == 1008) {
            return [
                'success'=>true,
                'cecharge_channel' => 'aliba',
                'order_number'     => $this->data['order_number'],
                'value'            =>json_encode($result),
            ];
        }

// var_dump($result);
        return [
            'success'=>false,
            'cecharge_channel' => 'aliba',
            'order_number'     => $this->data['order_number'],
            'value'            => json_encode($result),
        ];

    }

    protected function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
